#  udp_echo_daemon.rb
#
#  This file is part of myvnet.
#
#  Copyright (C) 2008  Filipe David Borba Manana,  fdmanana@gmail.com
#
#  myvnet is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  myvnet is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with myvnet.  If not, see <http://www.gnu.org/licenses/>.
 

require 'lib/daemons/generic_daemon'


module Daemon
  
  # A daemon whose purpose is to reply to Echo (over UDP) 
  # protocol packets. This is a protocol used for connectivity
  # testing (RFC 862). In GNU/Linux and *BSD systems, it is
  # implemented by the _inetd_ daemon.
  #
  class UdpEchoDaemon < Daemon::GenericDaemon
        
    def process(packet)
      return unless packet.has_udp?
      
      ip_pkt = packet.payload
      udp_pkt = ip_pkt.payload
      
      unless udp_pkt.dport == 7 and @net_addresses.include? ip_pkt.dst
        return
      end
      
      eth_reply = packet.dup
      eth_reply.dst = packet.src
      eth_reply.src = @hwaddress
      
      ip_reply = eth_reply.payload
      ip_reply.dst, ip_reply.src = ip_reply.src, ip_reply.dst
      
      udp_reply = ip_reply.payload
      udp_reply.dport, udp_reply.sport = udp_reply.sport, udp_reply.dport
      
      # UDP and IPv4 header checksum are the same...
      
      inject eth_reply
      
      true # packet processed
    end
        
  end
  
end
